import datetime
import logging
import os
import time
import wsgiref.handlers
import random
import cgi
import simplejson as JSON

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import py.datamodel

class Activity(webapp.RequestHandler):
    def get(self):
        self.post()
        
    def post(self):
        self.response.headers['Content-Type'] = 'text/xml'
        
        owner = self.request.get("owner")
        template_values = {}
        
        query = db.Query(py.datamodel.Preferences)
        query.filter("owner =", owner)
        userPreferences = query.get()
        
        item = {}
        item["guid"] = owner
        item["link"] = "http://orkut-scope.appspot.com/activity?owner=" + owner
        item["pubDate"] = datetime.date.today()            

        if userPreferences == None or userPreferences.feedPrefs == "Install":
            item["title"] = "just installed Sneak-O-Scope...."
            item["description"] = cgi.escape("can now monitor all visits to the profile, view visitor statistics and locations!! <br><img src = 'http://orkut-scope.appspot.com/img/logo.png'>") 
            userPreferences = py.datamodel.Preferences()
            userPreferences.owner = owner
            userPreferences.feedPrefs = "UserCount"
            userPreferences.totalCount = 1
            userPreferences.counters = '{"knownVisitors" : 0}' 
            userPreferences.put();
                

        else:
            query = db.Query(py.datamodel.Preferences)
            query.filter("owner =", "sneakoscope")
            userPrefs = query.get()
            sos_totalCount = long(userPrefs.totalCount)
            counters = JSON.loads(userPrefs.counters)
            sos_knownVisitors = 0
            if "knownVisitors" in counters:
                sos_knownVisitors = counters["knownVisitors"]


            query = db.Query(py.datamodel.Preferences)
            query.filter("owner =", owner)
            userPrefs = query.get()
            totalCount = long(userPrefs.totalCount)
            counters = JSON.loads(userPrefs.counters)
            knownVisitors = 0;
            
            if "knownVisitors" in counters:
                knownVisitors = counters["knownVisitors"]
            if totalCount == 0:
                totalCount = 1;
            
            option = int(random.random() * 10 % 8)
            
            if option == 0:
                item["title"] = "analyzed " + str(totalCount) + " visits on the profile page that were recorded using Sneak-O-Scope"
                item["description"] = cgi.escape("The application displays the location, time, and other interesting details about the visitor<br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 1:
                item["title"] = "was told that Sneak-O-Scope had recorded more than " + str(sos_totalCount) + " visits to user profiles"
                item["description"] = cgi.escape("Details like location, time of visit, length of visit, etc have been recorded <br><img src = 'http://orkut-scope.appspot.com/img/people.png'>"); 
            elif option == 2:
                item["title"] = "discovered that %s %% of visitors on the profile page don't have sneak-o-scope installed" % str(100 - (100 * knownVisitors / totalCount))
                item["description"] = cgi.escape("You can also install the application to check out such interesting details<br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 3:
                item["title"] = "discovered that %s %% of visitors on the profile page have sneak-o-scope installed" % str((100 * knownVisitors / totalCount))
                item["description"] = cgi.escape("You can also install the application to check out such interesting details<br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 4:
                item["title"] = "used the Sneak-O-Scope application to check out all the people who visited their profile page"
                item["description"] = cgi.escape("They were able to see visits even from people who have 'profile visits' turned off !! <br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 5:
                item["title"] = "found that %s %% of all visitors have Sneak O Scope application installed." % str(sos_knownVisitors * 100 / sos_totalCount)
                item["description"] = cgi.escape("All of them with the application can now see interesting statistics about visitors on their profile page<br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 6:
                item["title"] = "seems to have %s %% of total visitors recorded by Sneak-O-Scope." % str(totalCount * 100 / sos_totalCount)
                item["description"] = cgi.escape("Have you added application to see how popular you are on this social networking site ? <br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            elif option == 6:
                item["title"] = "just noticed that someone had visited their profile from a distant land. Thats quite a surprise now !! "
                item["description"] = cgi.escape("With the application you can see the places where people see your profile. You could be famous internationally !!  <br><img src = 'http://orkut-scope.appspot.com/img/visitor.jpg'>")
            
        template_values["itemList"] = [item];
        template_values["pubDate"] = datetime.date.today()
        template_values["buildDate"] = datetime.date.today()
        
        path = os.path.join(os.path.dirname(__file__), '../templates/feed.xml')
        path = os.path.abspath(path);
        self.response.out.write(template.render(path, template_values))
        
if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/activity', Activity)
      ],
      debug=True)

  wsgiref.handlers.CGIHandler().run(application)
